#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sqlite3
import os

def clear_all_data():
    """清空数据库中所有表的数据"""
    
    # 连接数据库
    conn = sqlite3.connect('performance.db')
    cursor = conn.cursor()
    
    try:
        # 获取所有表名
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = cursor.fetchall()
        
        print("开始清空数据库中的所有数据...")
        
        # 清空每个表的数据
        for table in tables:
            table_name = table[0]
            if table_name != 'sqlite_sequence':  # 跳过系统表
                cursor.execute(f"DELETE FROM {table_name}")
                print(f"已清空表: {table_name}")
        
        # 重置自增ID
        cursor.execute("DELETE FROM sqlite_sequence")
        print("已重置所有自增ID")
        
        # 提交更改
        conn.commit()
        print("数据清空完成！")
        
        # 显示清空后的统计信息
        print("\n清空后的表统计:")
        for table in tables:
            table_name = table[0]
            if table_name != 'sqlite_sequence':
                cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
                count = cursor.fetchone()[0]
                print(f"  {table_name}: {count} 条记录")
        
    except Exception as e:
        print(f"清空数据时出错: {str(e)}")
        conn.rollback()
    
    finally:
        conn.close()

def clear_upload_files():
    """清空uploads文件夹中的文件"""
    upload_folder = 'uploads'
    
    if os.path.exists(upload_folder):
        print(f"\n开始清空 {upload_folder} 文件夹...")
        
        files = os.listdir(upload_folder)
        if files:
            for file in files:
                file_path = os.path.join(upload_folder, file)
                try:
                    os.remove(file_path)
                    print(f"已删除文件: {file}")
                except Exception as e:
                    print(f"删除文件 {file} 失败: {str(e)}")
            print(f"uploads文件夹清空完成！")
        else:
            print("uploads文件夹已经是空的")
    else:
        print("uploads文件夹不存在")

def clear_test_files():
    """清空测试Excel文件"""
    print("\n开始清空测试Excel文件...")
    
    # 查找所有测试Excel文件
    test_files = []
    for file in os.listdir('.'):
        if file.startswith('test_') and file.endswith('.xlsx'):
            test_files.append(file)
    
    if test_files:
        for file in test_files:
            try:
                os.remove(file)
                print(f"已删除测试文件: {file}")
            except Exception as e:
                print(f"删除测试文件 {file} 失败: {str(e)}")
        print("测试文件清空完成！")
    else:
        print("没有找到测试Excel文件")

if __name__ == '__main__':
    print("=" * 50)
    print("数据清空工具")
    print("=" * 50)
    
    # 清空数据库数据
    clear_all_data()
    
    # 清空上传文件
    clear_upload_files()
    
    # 清空测试文件
    clear_test_files()
    
    print("\n" + "=" * 50)
    print("所有数据清空完成！")
    print("=" * 50)